package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"info/db"
	"io/ioutil"
	"strconv"
)

type StaticConfig struct {
	Base      string
	Resources []string
}

type Config struct {
	Env        string
	HttpPort   string
	HttpsPort  string
	Static     StaticConfig
	Templates  []string
	DataSource string
}

func getConfig() *Config {
	confFile := flag.String("c", "conf.json", "global config file, type json.")
	data, er := ioutil.ReadFile(*confFile)
	throwFatalError(er)

	var config = &Config{
		Env:       gin.DebugMode,
		HttpPort:  "9080",
		HttpsPort: "9443",
		Static: StaticConfig{
			Base:      "./static/",
			Resources: []string{"js", "css", "fonts", "images"},
		},
		Templates:  []string{"templates/**.html"},
		DataSource: "host=localhost port=5432 user=postgres password=postgres dbname=info sslmode=disable",
	}
	er = json.Unmarshal(data, config)
	throwFatalError(er)

	base := []rune(config.Static.Base)
	if base[len(base)-1] != '/' {
		config.Static.Base += "/"
	}

	return config
}

//

type Seo struct {
	Title       string
	Description string
	Keywords    []string
	Url         string
	Image       string
}

func start(conf *Config) error {
	gin.SetMode(conf.Env)

	r := gin.Default()

	r.Use(gin.Logger()).Use(gin.Recovery())
	r.Use(func(ctx *gin.Context) {
		uri := ctx.Request.RequestURI
		fmt.Println("URI: ", uri, )
		ctx.Next()
	})

	for _, resource := range conf.Static.Resources {
		r.Static("/"+resource, conf.Static.Base+"/"+resource)
	}

	for _, temp := range conf.Templates {
		r.LoadHTMLGlob(temp)
	}

	// page
	// 404
	r.NoRoute(func(ctx *gin.Context) {
		ctx.HTML(404, "404", nil)
	})
	// index
	r.GET("/", func(ctx *gin.Context) {
		list := db.ListArticle(5, 0)
		fmt.Println("list", list)
		ctx.HTML(200, "index", gin.H{
			"Seo": &Seo{
				Title:       "首页",
				Description: "详细情况",
				Keywords:    []string{"加持"},
			},
			"List": list,
		})
	})
	// list
	r.GET("/list/:page", func(ctx *gin.Context) {
		page := ctx.Param("page")
		fmt.Println("page:", page)
	})
	// article
	r.GET("/article/:id", func(ctx *gin.Context) {
		id0 := ctx.Param("id")
		id, er := strconv.ParseInt(id0, 10, 64)
		if er != nil {
			ctx.Status(404)
			return
		}

		article := db.GetArticle(int64(id))
		if nil == article {
			ctx.Status(404)
			return
		}
		fmt.Println("id:", id)
		ctx.HTML(200, "article", gin.H{
			"Seo": &Seo{
				Title:       "首页",
				Description: "详细情况",
				Keywords:    []string{"加持"},
			},
			"Article": article,
		})
	})

	// api

	return r.Run(":" + conf.HttpPort)
}
func main() {
	conf := getConfig()

	er := db.InitDb(conf.DataSource)
	throwFatalError(er)

	er = start(conf)
	throwFatalError(er)
}

func throwFatalError(err error) {
	if err != nil {
		panic(err)
	}
}
